package com.ruoyi.file.service;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service("qiniuServiceImpl")
public class QiniuServiceImpl implements ISysFileService {

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.zone}")
    private String zone;

    @Value("${qiniu.domain}")
    private String domain;

    @Override
    public String uploadFile(MultipartFile file) throws IOException
    {
        System.out.println();
        Configuration cfg = new Configuration(Zone.autoZone());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file.getBytes(), null, upToken);
            if (response.isOK()) {
                return domain +"/"+ response.jsonToMap().get("key").toString();
            }
        } catch (QiniuException ex) {
            throw new IOException(ex.getMessage());
        }
        return null;
    }
}